package com.wish.auth.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.wish.auth.feign.UserFeign;
import com.wish.dto.login.JsonResult;
import com.wish.dto.login.UserDto;
import com.wish.dto.login.UserVo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController {

    @Value("${jwt.key}")//取配置文件里的jwt.key
    private String jwtKey;
    @Autowired
    UserFeign userFeign;

    @PostMapping("/login")
    public JsonResult<UserVo> login(@RequestBody UserDto userDto){
        UserVo userVo = new UserVo();
        if (StringUtils.isEmpty(userDto.getUsername()) || StringUtils.isEmpty(userDto.getPassword())) {
            return JsonResult.faild("用户名或密码不能为空");
        }
        //调用
        UserDto loginUserDto = userFeign.getByUsername(userDto.getUsername());
        if (loginUserDto == null) {
            return JsonResult.faild("用户名不存在");
        }
        String password = SecureUtil.md5(userDto.getPassword());
        System.out.println(password);
        if (!password.equals(loginUserDto.getPassword())) {
            return JsonResult.faild("密码不对");
        }
        //使用JWT生成token
        String token = JWT.create()
                .setKey(jwtKey.getBytes())
                .setPayload("username", loginUserDto.getUsername())
                .setExpiresAt(DateUtil.offsetDay(DateUtil.date(), 1))
                .sign();
        userVo.setToken(token);
        userVo.setLoginTime(new DateTime());
        return JsonResult.successd(userVo);
    }


}
